/**
 * ContactDetail.java
 *
 *	
 */
package com.ghc.androidexample.user;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;
import android.widget.TextView;

import com.ghc.androidexample.R;

/**
 * 
 */
public class ContactDetail extends Dialog implements LoaderCallbacks<Cursor> {
	@SuppressLint("InlinedApi")
	private static final String[] PROJECTION = {
			Contacts._ID,
			Contacts.LOOKUP_KEY,
			Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? Contacts.DISPLAY_NAME_PRIMARY
					: Contacts.DISPLAY_NAME, Email.ADDRESS };
	private static final String[] SELECTION = {};

	private TextView mTvName;
	private TextView mTvMobile;

	public ContactDetail(Activity activity, Uri uri) {
		super(activity);

		setContentView(R.layout.contact_detail);

		setTitle("Detail");
		
		mTvName = (TextView) findViewById(R.id.tvName);
		mTvMobile = (TextView) findViewById(R.id.tvMobile);

		Bundle bundle = new Bundle();
		bundle.putParcelable("Uri", uri);
		activity.getLoaderManager().initLoader(0, bundle, this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.LoaderManager.LoaderCallbacks#onCreateLoader(int,
	 * android.os.Bundle)
	 */
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Uri uri = (Uri) args.getParcelable("Uri");

		CursorLoader cursorLoader = new CursorLoader(getContext(), uri,
				PROJECTION, null, null, null);
		return cursorLoader;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.content
	 * .Loader, java.lang.Object)
	 */
	@SuppressLint("InlinedApi")
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		cursor.moveToFirst();
		int nameIndex = cursor
				.getColumnIndex(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? Contacts.DISPLAY_NAME_PRIMARY
						: Contacts.DISPLAY_NAME);
		int emailIndex = cursor.getColumnIndex(Email.ADDRESS);
		if (nameIndex != -1) {
			String name = cursor.getString(nameIndex);
			mTvName.setText(name);
		}
		if (emailIndex != -1) {
			String email = cursor.getString(emailIndex);
			mTvMobile.setText(email);
		}
		cursor.close();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.content
	 * .Loader)
	 */
	@Override
	public void onLoaderReset(Loader<Cursor> loader) {

	}
}
